<template>
    <div class="classroom-management">
      <div class="page-header">
        <h2>教室管理</h2>
      </div>
  
      <!-- 搜索表单 -->
      <el-card class="search-card" shadow="never">
        <el-form :model="searchForm" :inline="true" class="search-form">
          <el-form-item label="教室编号">
            <el-input v-model="searchForm.classroomNo" placeholder="请输入教室编号" clearable style="width: 160px" />
          </el-form-item>
          <el-form-item label="教室名称">
            <el-input v-model="searchForm.classroomName" placeholder="请输入教室名称" clearable style="width: 160px" />
          </el-form-item>
          <el-form-item label="教室类型">
            <el-select v-model="searchForm.classroomType" placeholder="请选择类型" clearable style="width: 160px">
              <el-option 
                v-for="type in classroomTypes" 
                :key="type" 
                :label="type" 
                :value="type" 
              />
            </el-select>
          </el-form-item>
          <el-form-item label="所在楼栋">
            <el-select v-model="searchForm.building" placeholder="请选择楼栋" clearable style="width: 160px">
              <el-option 
                v-for="building in buildings" 
                :key="building" 
                :label="building" 
                :value="building" 
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
              <el-option label="可用" :value="1" />
              <el-option label="不可用" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch"><el-icon><Search /></el-icon>搜索</el-button>
            <el-button @click="handleReset"><el-icon><Refresh /></el-icon>重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
  
      <!-- 操作按钮 -->
      <el-card class="action-card" shadow="never">
        <div class="action-buttons">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>新增教室
          </el-button>
          <el-button type="danger" :disabled="selectedIds.length === 0" @click="handleBatchDelete">
            <el-icon><Delete /></el-icon>批量删除
          </el-button>
          <el-button type="info" @click="handleExport">
            <el-icon><Download /></el-icon>导出数据
          </el-button>
        </div>
      </el-card>
  
      <!-- 数据表格 -->
      <el-card class="table-card" shadow="never">
        <el-table 
          :data="classroomList" 
          v-loading="loading" 
          stripe 
          border 
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="classroomNo" label="教室编号" width="120" />
          <el-table-column prop="classroomName" label="教室名称" width="150" />
          <el-table-column prop="capacity" label="容量" width="80" />
          <el-table-column prop="classroomType" label="类型" width="120">
            <template #default="scope">
              <el-tag :type="getClassroomTypeTag(scope.row.classroomType)">
                {{ scope.row.classroomType }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="building" label="楼栋" width="100" />
          <el-table-column prop="floor" label="楼层" width="80" />
          <el-table-column prop="equipment" label="设备配置" width="200" show-overflow-tooltip />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                {{ scope.row.status === 1 ? '可用' : '不可用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="classroomRemark" label="备注" width="150" show-overflow-tooltip />
          <el-table-column prop="createTime" label="创建时间" width="160">
            <template #default="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="360" fixed="right">
            <template #default="scope">
              <el-button type="info" size="small" @click="handleView(scope.row)">详情</el-button>
              <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button :type="scope.row.status === 1 ? 'warning' : 'success'" size="small" @click="handleToggleStatus(scope.row)">{{ scope.row.status === 1 ? '禁用' : '启用' }}</el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
  
      <!-- 新增/编辑教室对话框 -->
      <el-dialog v-model="dialogVisible" :title="dialogTitle" width="800px" @close="handleDialogClose">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="教室编号" prop="classroomNo">
                <el-input v-model="form.classroomNo" placeholder="请输入教室编号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="教室名称" prop="classroomName">
                <el-input v-model="form.classroomName" placeholder="请输入教室名称" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="教室容量" prop="capacity">
                <el-input-number v-model="form.capacity" :min="1" :max="500" placeholder="容量" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="教室类型" prop="classroomType">
                <el-select v-model="form.classroomType" placeholder="请选择类型" style="width: 100%">
                  <el-option label="普通教室" value="普通教室" />
                  <el-option label="实验室" value="实验室" />
                  <el-option label="机房" value="机房" />
                  <el-option label="多媒体教室" value="多媒体教室" />
                  <el-option label="语音室" value="语音室" />
                  <el-option label="画室" value="画室" />
                  <el-option label="会议室" value="会议室" />
                  <el-option label="阶梯教室" value="阶梯教室" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="所在楼栋" prop="building">
                <el-input v-model="form.building" placeholder="请输入楼栋" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="楼层" prop="floor">
                <el-input-number v-model="form.floor" :min="1" :max="20" placeholder="楼层" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="设备配置" prop="equipment">
            <el-input v-model="form.equipment" type="textarea" :rows="3" placeholder="请输入设备配置信息" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio :label="1">可用</el-radio>
              <el-radio :label="0">不可用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注" prop="classroomRemark">
            <el-input v-model="form.classroomRemark" type="textarea" :rows="3" placeholder="请输入备注信息" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </span>
        </template>
      </el-dialog>
  
      <!-- 详情对话框 -->
      <el-dialog v-model="detailDialogVisible" title="教室详情" width="600px">
        <div class="detail-content">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="教室编号">{{ detailData.classroomNo }}</el-descriptions-item>
            <el-descriptions-item label="教室名称">{{ detailData.classroomName }}</el-descriptions-item>
            <el-descriptions-item label="容量">{{ detailData.capacity }}人</el-descriptions-item>
            <el-descriptions-item label="教室类型">{{ detailData.classroomType }}</el-descriptions-item>
            <el-descriptions-item label="所在楼栋">{{ detailData.building }}</el-descriptions-item>
            <el-descriptions-item label="楼层">{{ detailData.floor }}层</el-descriptions-item>
            <el-descriptions-item label="设备配置" :span="2">{{ detailData.equipment || '无' }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="detailData.status === 1 ? 'success' : 'danger'">
                {{ detailData.status === 1 ? '可用' : '不可用' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ formatDate(detailData.createTime) }}</el-descriptions-item>
            <el-descriptions-item label="更新时间" :span="2">{{ formatDate(detailData.updateTime) }}</el-descriptions-item>
            <el-descriptions-item label="备注" :span="2">{{ detailData.classroomRemark || '无' }}</el-descriptions-item>
          </el-descriptions>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="detailDialogVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Search, Refresh, Plus, Delete, Download } from '@element-plus/icons-vue'
  import { 
    getClassroomPage,
    getClassroomById,
    addClassroom, 
    updateClassroom, 
    deleteClassroom,
    batchDeleteClassrooms,
    updateClassroomStatus,
    getClassroomTypes,
    getBuildings
  } from '../api/classroom'
  
  // 搜索表单
  const searchForm = reactive({
    classroomNo: '',
    classroomName: '',
    classroomType: '',
    building: '',
    status: null
  })
  
  // 分页
  const pagination = reactive({ currentPage: 1, pageSize: 10, total: 0 })
  const classroomList = ref([])
  const loading = ref(false)
  const selectedIds = ref([])
  
  // 对话框
  const dialogVisible = ref(false)
  const dialogTitle = ref('')
  const isEdit = ref(false)
  const detailDialogVisible = ref(false)
  const detailData = ref({})
  
  // 基础数据
  const classroomTypes = ref([])
  const buildings = ref([])
  
  // 表单数据
  const form = reactive({
    classroomId: null,
    classroomNo: '',
    classroomName: '',
    capacity: 50,
    classroomType: '',
    building: '',
    floor: 1,
    equipment: '',
    status: 1,
    classroomRemark: ''
  })
  
  // 表单验证规则
  const rules = {
    classroomNo: [{ required: true, message: '请输入教室编号', trigger: 'blur' }],
    classroomName: [{ required: true, message: '请输入教室名称', trigger: 'blur' }],
    capacity: [{ required: true, message: '请输入教室容量', trigger: 'blur' }],
    classroomType: [{ required: true, message: '请选择教室类型', trigger: 'change' }],
    building: [{ required: true, message: '请输入所在楼栋', trigger: 'blur' }],
    floor: [{ required: true, message: '请输入楼层', trigger: 'blur' }],
    status: [{ required: true, message: '请选择状态', trigger: 'change' }]
  }
  
  const formRef = ref()
  
  // 工具函数
  const getClassroomTypeTag = (type) => {
    const typeMap = {
      '普通教室': 'info',
      '实验室': 'warning',
      '机房': 'success',
      '多媒体教室': 'primary',
      '语音室': 'danger',
      '画室': 'success',
      '会议室': 'info',
      '阶梯教室': 'primary'
    }
    return typeMap[type] || 'info'
  }
  
  const formatDate = (date) => {
    if (!date) return ''
    return new Date(date).toLocaleString('zh-CN')
  }
  
  // 获取教室列表
  const fetchClassroomList = async () => {
    loading.value = true
    try {
      const params = {
        page: pagination.currentPage,
        pageSize: pagination.pageSize,
        ...searchForm
      }
      const response = await getClassroomPage(params)
      classroomList.value = response.data.records
      pagination.total = response.data.total
    } catch (error) {
      console.error('获取教室列表失败:', error)
      ElMessage.error('获取教室列表失败')
    } finally {
      loading.value = false
    }
  }
  
  // 获取基础数据
  const fetchBasicData = async () => {
    try {
      const [typesResponse, buildingsResponse] = await Promise.all([
        getClassroomTypes(),
        getBuildings()
      ])
      classroomTypes.value = typesResponse.data
      buildings.value = buildingsResponse.data
    } catch (error) {
      console.error('获取基础数据失败:', error)
    }
  }
  
  // 搜索
  const handleSearch = () => {
    pagination.currentPage = 1
    fetchClassroomList()
  }
  
  // 重置
  const handleReset = () => {
    Object.keys(searchForm).forEach(key => {
      searchForm[key] = key === 'status' ? null : ''
    })
    pagination.currentPage = 1
    fetchClassroomList()
  }
  
  // 分页
  const handleSizeChange = (size) => {
    pagination.pageSize = size
    pagination.currentPage = 1
    fetchClassroomList()
  }
  
  const handleCurrentChange = (page) => {
    pagination.currentPage = page
    fetchClassroomList()
  }
  
  // 选择变化
  const handleSelectionChange = (selection) => {
    selectedIds.value = selection.map(item => item.classroomId)
  }
  
  // 新增
  const handleAdd = () => {
    dialogTitle.value = '新增教室'
    isEdit.value = false
    resetForm()
    dialogVisible.value = true
  }
  
  // 编辑
  const handleEdit = (row) => {
    dialogTitle.value = '编辑教室'
    isEdit.value = true
    Object.keys(form).forEach(k => form[k] = row[k] ?? '')
    dialogVisible.value = true
  }
  
  // 查看详情
  const handleView = (row) => {
    detailData.value = { ...row }
    detailDialogVisible.value = true
  }
  
  // 删除
  const handleDelete = (row) => {
    ElMessageBox.confirm(`确定要删除教室 "${row.classroomName}" 吗？`, '删除确认', { 
      confirmButtonText: '确定', 
      cancelButtonText: '取消', 
      type: 'warning' 
    })
      .then(async () => {
        await deleteClassroom(row.classroomId)
        ElMessage.success('删除成功')
        fetchClassroomList()
      })
      .catch(() => ElMessage.info('已取消删除'))
  }
  
  // 批量删除
  const handleBatchDelete = () => {
    if (selectedIds.value.length === 0) {
      ElMessage.warning('请选择要删除的教室')
      return
    }
    
    ElMessageBox.confirm(`确定要删除选中的 ${selectedIds.value.length} 个教室吗？`, '批量删除确认', { 
      confirmButtonText: '确定', 
      cancelButtonText: '取消', 
      type: 'warning' 
    })
      .then(async () => {
        await batchDeleteClassrooms(selectedIds.value)
        ElMessage.success('批量删除成功')
        selectedIds.value = []
        fetchClassroomList()
      })
      .catch(() => ElMessage.info('已取消删除'))
  }
  
  // 切换状态
  const handleToggleStatus = async (row) => {
    const newStatus = row.status === 1 ? 0 : 1
    const action = newStatus === 1 ? '启用' : '禁用'
    
    try {
      await updateClassroomStatus(row.classroomId, newStatus)
      ElMessage.success(`${action}成功`)
      fetchClassroomList()
    } catch (error) {
      ElMessage.error(`${action}失败`)
    }
  }
  
  // 导出
  const handleExport = () => {
    ElMessage.info('导出功能开发中...')
  }
  
  // 提交表单
  const handleSubmit = async () => {
    const valid = await formRef.value.validate()
    if (!valid) return
    
    try {
      if (isEdit.value) {
        await updateClassroom(form)
        ElMessage.success('编辑成功')
      } else {
        await addClassroom(form)
        ElMessage.success('新增成功')
      }
      dialogVisible.value = false
      fetchClassroomList()
    } catch (error) {
      console.error('操作失败:', error)
    }
  }
  
  // 重置表单
  const resetForm = () => {
    Object.keys(form).forEach(key => {
      if (key === 'capacity') {
        form[key] = 50
      } else if (key === 'floor') {
        form[key] = 1
      } else if (key === 'status') {
        form[key] = 1
      } else {
        form[key] = key === 'classroomId' ? null : ''
      }
    })
  }
  
  // 关闭对话框
  const handleDialogClose = () => {
    resetForm()
    formRef.value?.resetFields()
  }
  
  // 初始化
  onMounted(() => {
    fetchClassroomList()
    fetchBasicData()
  })
  </script>
  
  <style scoped>
  .classroom-management {
    padding: 20px;
  }
  
  .page-header {
    margin-bottom: 20px;
  }
  
  .page-header h2 {
    margin: 0;
    color: #303133;
  }
  
  .search-card, .action-card, .table-card {
    margin-bottom: 20px;
  }
  
  .search-form {
    margin-bottom: 0;
  }
  
  .action-buttons {
    display: flex;
    gap: 10px;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
  
  .detail-content {
    padding: 20px 0;
  }
  
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
  </style>
























